#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sstream>
#include "Log.hpp"

class Util
{
public:
    // 因为文件可能是文本也可能是二进制文件（图片，视频，音频），所以读取时得按二进制的方式去读
    static bool ReadFile(const std::string &path, std::string *fileContent)
    {
        //先获取文件大小
        struct stat st;
        int n = stat(path.c_str(), &st);
        if(n < 0)
        {
            return false;
        }
        int size = st.st_size;
        //调整string的空间
        fileContent->resize(size);
        //读取
        int fd = open(path.c_str(), O_RDONLY);
        if (fd < 0)
        {
            return false;
        }
        read(fd, (char*)fileContent->c_str(), size);
        close(fd);
        logMessage(Info, "read file %s done", path.c_str());
        return true;
    }

    static std::string ReadOneLine(std::string &message, const std::string &sep)
    {
        auto pos = message.find(sep);
        if(pos == std::string::npos)
        {
            return "";
        }
        std::string s = message.substr(0, pos);
        message.erase(0, pos + sep.size());
        return s;
    }
    
    static bool ParseRequestLine(const std::string &line, std::string *method, std::string *url, std::string *httpVersion)
    {
        std::stringstream ss(line);
        ss >> *method >> *url >> *httpVersion;
        return true;
    }

};
